package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.R;
import com.example.domain.User;

import com.example.service.UserService;
import com.example.utils.ValidateCodeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user) {

        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)) {

            String s = ValidateCodeUtils.generateValidateCode(4).toString();

            System.out.println("code" + s);

            redisTemplate.opsForValue().set(phone, s,5L, TimeUnit.MINUTES);

            return R.success("发送成功,验证码为: "+s);
        }

        return R.error("发送失败");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody Map map, HttpSession session) {


        String phone = map.get("phone").toString();

        String code = map.get("code").toString();

        Object attribute = redisTemplate.opsForValue().get(phone);



        if (attribute != null && attribute.equals(code)) {

            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>();

            wrapper.eq(User::getPhone, phone);

            User one = userService.getOne(wrapper);

            if (one == null) {

                one = new User();

                one.setPhone(phone);

                one.setStatus(1);

                userService.save(one);
            }
            session.setAttribute("user", one.getId());

            redisTemplate.delete(phone);

            return R.success("登录成功");

        }

        return R.error("登录失败");
    }

    @PostMapping("/loginout")
    public R logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return R.success("退出成功！");
    }



}
